// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenstore/scrubcontext.h"

#include <zencore/workthreadpool.h>

namespace zen {

ScrubDeadlineExpiredException::ScrubDeadlineExpiredException() : std::runtime_error("scrubbing deadline expired")
{
}

ScrubDeadlineExpiredException::~ScrubDeadlineExpiredException()
{
}

//////////////////////////////////////////////////////////////////////////

ScrubContext::ScrubContext(WorkerThreadPool& InWorkerThreadPool, std::chrono::steady_clock::time_point Deadline)
: m_WorkerThreadPool(InWorkerThreadPool)
, m_Deadline(Deadline)
{
}

ScrubContext::~ScrubContext()
{
}

HashKeySet
ScrubContext::BadCids() const
{
	RwLock::SharedLockScope _(m_Lock);
	return m_BadCid;
}

bool
ScrubContext::IsBadCid(const IoHash& Cid) const
{
	RwLock::SharedLockScope _(m_Lock);
	return m_BadCid.ContainsHash(Cid);
}

void
ScrubContext::ReportBadCidChunks(std::span<IoHash> BadCasChunks)
{
	RwLock::ExclusiveLockScope _(m_Lock);
	m_BadCid.AddHashesToSet(BadCasChunks);
}

bool
ScrubContext::IsWithinDeadline() const
{
	return std::chrono::steady_clock::now() < m_Deadline;
}

void
ScrubContext::ThrowIfDeadlineExpired() const
{
	if (IsWithinDeadline())
		return;

	throw ScrubDeadlineExpiredException();
}

}  // namespace zen
